package com.ysd.shiro.serviceImpl;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ysd.common.utils.RedisUtils;
import com.ysd.shiro.entity.User;
import com.ysd.shiro.mapper.UserMapper;
import com.ysd.shiro.service.UserService;
import com.ysd.shiro.util.CacheUser;
import com.ysd.shiro.util.ShiroUtils;
import com.ysd.shiro.web.exception.LoginException;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;

    @Override
    public CacheUser login(String username, String password) {

        // 获取Subject实例对象，用户实例
        Subject currentUser = SecurityUtils.getSubject();

        // 将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        CacheUser cacheUser;

        // 认证
        try {
            // 传到 ShiroRealm 类中的方法进行认证
            currentUser.login(token);
            // 构建缓存用户信息返回给前端
            User user = (User) currentUser.getPrincipals().getPrimaryPrincipal();
            cacheUser = CacheUser.builder().token(currentUser.getSession().getId().toString()).build();
            //进行对象之间属性的赋值，避免通过get、set方法一个一个属性的赋值
            BeanUtils.copyProperties(user, cacheUser);
            //把用户的id存到redis中
            //String userId = user.getUserId()+"";
            //RedisUtils.set(user.getPhone(),userId);
            log.info("CacheUser is {}", cacheUser.toString());
        } catch (UnknownAccountException e) {
            log.error("账户不存在异常：", e);
            throw new LoginException("账号不存在!", e);
        } catch (IncorrectCredentialsException e) {
            log.error("凭据错误（密码错误）异常：", e);
            throw new LoginException("密码不正确!", e);
        } catch (AuthenticationException e) {
            log.error("身份验证异常:", e);
            throw new LoginException("用户验证失败!", e);
        }
        return cacheUser;
    }


    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
    
    @Override
	public int addUser(User user) {      
    	//给明文密码加密
    	String newPassword = ShiroUtils.sha256(user.getLoginPassword(), "123");
    	user.setLoginPassword(newPassword);
    	user.setSalt("123");
		return userMapper.insertUser(user);
	}
    
    /**
	  * 按照id进行查询
	  * @param id
	  * @return
	*/
	public User findUserById(int userId) {
		return userMapper.findById(userId);
	};
	
	
	public int delUserById(int userId) {
		return userMapper.delete(userId);
	};
}
